package com.haocang.szgm.activity.comm;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.haocang.commonlib.loadingdialog.LoadingDialog;
import com.haocang.commonlib.otherutil.ImageUtils;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.adapter.ImageFileAdapter;
import com.haocang.szgm.activity.bean.FileIndexBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.commonlib.recyclerView.BaseAdapter;
import com.haocang.szgm.utils.tools.CustomDialog;
import com.haocang.szgm.utils.tools.GetCommonParameters;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import net.tsz.afinal.FinalActivity;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_LOW_MEMORY;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_NO_VIDEO_TRACK;
import static com.qiniu.pili.droid.shortvideo.PLErrorCode.ERROR_SRC_DST_SAME_FILE_PATH;

/**===============================================
 * 创建时间：2018/11/30 17:24
 * 编 写 人：ShenC
 * 方法说明：包含多媒体文件上传功能
 *================================================
 * 修改内容：      修改时间：      修改人：
 *===============================================*/
public abstract class CommMediaActivity extends FinalActivity {


	protected RecyclerView mRecyclerView;
	protected ImageFileAdapter imageFileAdapter;
	protected static Context mContext;
	protected LinearLayout media;
	protected LinearLayout bar_lin;
	protected LinearLayout iv_back;
	protected TextView tv_name;
	protected LinearLayout iv_more;
	protected ImageView iv_more_icon;
	protected String capturePath = null;

	protected final int  REQUEST_CODE_PICK_IMAGE = 1111;//相册
	protected final int  REQUEST_CODE_CAPTURE_CAMEIA = 2222;//拍照
	protected final int  REQUEST_CODE_CAPTURE_VIDEO = 3333;//录像

	protected ImageView add_video1;
	protected ImageView iv_video_close;


	protected List<FileIndexBean> filelist = new ArrayList<>();
	protected List<File> vediofilelist = new ArrayList<>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//TODO Auto-generated method stub
		mContext = this;
		initWindows();
		super.onCreate(savedInstanceState);
		setContentView(getLayoutResourceId());

		initView();

		initEvent();

		filelist.add(new FileIndexBean(true));
		imageFileAdapter.setNewData(filelist);

	}

	private  void  initView(){

		media  = findViewById(R.id.media);
		bar_lin = findViewById(R.id.bar_lin);
		iv_back = findViewById(R.id.iv_back);
		tv_name = findViewById(R.id.tv_name);
		iv_more = findViewById(R.id.iv_more);
		iv_more_icon = findViewById(R.id.iv_more_icon);

		add_video1 = findViewById(R.id.add_video1);
		iv_video_close = findViewById(R.id.iv_video_close);
		iv_video_close.setVisibility(View.GONE);
		mRecyclerView = findViewById(R.id.recyclerView);

		tv_name.setText(showTitleName());

		if(showMoreIcon() == 0){
			iv_more.setVisibility(View.GONE);
		}else{
			iv_more.setVisibility(View.VISIBLE);
			iv_more_icon.setBackgroundResource(showMoreIcon());
		}

		//tv_name.setText("温州智慧排水");

		if (showNavigation()) {
			bar_lin.setVisibility(View.VISIBLE);
		}else{
			bar_lin.setVisibility(View.GONE);
		}


		if (showMedia()) {
			media.setVisibility(View.VISIBLE);
		}else{
			media.setVisibility(View.GONE);
		}


		imageFileAdapter = new ImageFileAdapter(mContext);
		mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL) {
			@Override
			public boolean canScrollVertically() {
				return false;
			}
		});

		mRecyclerView.setAdapter(imageFileAdapter);
	}



	/**
	 * 获取布局文件
	 * @return
	 */
	protected abstract int getLayoutResourceId();

	/**
	 * 是否显示bar
	 * @return
	 */
	protected abstract boolean showNavigation();

	/**
	 * 多媒体
	 * @return
	 */
	protected abstract boolean showMedia();

	/**
	 * 设置显示的图标,0为隐藏
	 * @return
	 */
	protected abstract int showMoreIcon();

	/**
	 * 设置标题
	 * @return
	 */
	protected abstract String showTitleName();

	@SuppressLint("NewApi")
	private void initWindows() {
		Window window = getWindow();
		int color = getResources().getColor(android.R.color.transparent);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
					// | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			//设置状态栏颜色
			window.setStatusBarColor(color);
			//设置导航栏颜色
			// window.setNavigationBarColor(color);
			ViewGroup contentView = ((ViewGroup) findViewById(android.R.id.content));
			View childAt = contentView.getChildAt(0);
			if (childAt != null) {
				childAt.setFitsSystemWindows(true);
			}
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			//透明状态栏
			window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			//透明导航栏
			// window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			//设置contentview为fitsSystemWindows
			ViewGroup contentView = (ViewGroup) findViewById(android.R.id.content);
			View childAt = contentView.getChildAt(0);
			if (childAt != null) {
				childAt.setFitsSystemWindows(true);
			}
			//给statusbar着色
			View view = new View(mContext);
			view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()));
			view.setBackgroundColor(color);
			contentView.addView(view);
		}
	}
	/**
	 * 获取导航栏高度
	 * @return 导航栏高度
	 */
	public static int getNavigationBarHeight() {
		int resourceId = mContext.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
		return mContext.getResources().getDimensionPixelSize(resourceId);
	}

	/**
	 * 获取状态栏高度
	 * @return 状态栏高度
	 */
	private static int getStatusBarHeight() {
		// 获得状态栏高度
		int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
		return mContext.getResources().getDimensionPixelSize(resourceId);
	}


	protected  void ToastShow(String msg){
		Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
	}


	private void initEvent(){

		add_video1.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {

				if(vediofilelist.size() > 0){
					//ToastShow("预览视频");
				}else{
					getVideoFromCamera();
				}
			}
		});

		iv_video_close.setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
				vediofilelist.clear();
				add_video1.setImageResource(R.mipmap.icon_addpic_unfocused);
				iv_video_close.setVisibility(View.GONE);
			}
		});

		imageFileAdapter.setOnItemChildClickListener(new BaseAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseAdapter adapter, View v, int position) {
				FileIndexBean fileItem = imageFileAdapter.getItem(position);

				if (v.getId() == R.id.iv_close) {
					//删除fileList
					filelist.remove(fileItem);
					imageFileAdapter.setNewData(filelist);
					return;
				}

				if (v.getId() == R.id.iv) {

					if(position == filelist.size() - 1){

						if(filelist.size() <= 8){
							Camera();
						}else{
							ToastShow("目前图片最大支持8张！");
						}
					}else{
						//ToastShow("预览");
					}
				}

			}
		});


	}


	protected void Camera(){
		CustomDialog.Builder builder = new CustomDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("获取图片途径");
		builder.setPositiveButton("拍照", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				getImageFromCamera();
			}
		});

		builder.setNegativeButton("相册",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						getImageFromAlbum();
					}
				});

		builder.create().show();

	}

	protected void getImageFromAlbum() {
		Intent intent;
		if (Build.VERSION.SDK_INT < 19) {
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.setType("image/*");
		} else {
			intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		}
		startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);

	}


	protected void getVideoFromCamera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			String out_file_path = Environment.getExternalStorageDirectory().getPath()+"/"+ Config.APP_Code+"/video/";
			File dir = new File(out_file_path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			capturePath = out_file_path + GetCommonParameters.getNowTimetoString() + ".wmv";
			intent.putExtra(MediaStore.EXTRA_OUTPUT,  GetCommonParameters.GetFileProviderUri(mContext,capturePath));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);//限制录制时间10秒
			startActivityForResult(intent, REQUEST_CODE_CAPTURE_VIDEO);
			//ToastShow("视频只能录制10秒！");
		}
		else {
			Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
		}
	}


	protected void getImageFromCamera() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
			String out_file_path = Environment.getExternalStorageDirectory().getPath()+"/"+ Config.APP_Code+"/camera/";
			File dir = new File(out_file_path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			capturePath = out_file_path + GetCommonParameters.getNowTimetoString() + ".jpg";
			intent.putExtra(MediaStore.EXTRA_OUTPUT,  GetCommonParameters.GetFileProviderUri(mContext,capturePath));
			intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
			startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);
		}
		else {
			Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
		}
	}


	protected void showImage(String ImgUrl) {

		//删除为空的文件
		for(FileIndexBean m :filelist){
			if(m.isAdd()){filelist.remove(m);}
		}

		filelist.add(new FileIndexBean(filelist.size()+1,ImgUrl));
		filelist.add(new FileIndexBean(true));
		imageFileAdapter.setNewData(filelist);



	}





	protected void showVideoImage(String videoUrl) {
		File file = new File(videoUrl);
		vediofilelist.add(file);
		iv_video_close.setVisibility(View.VISIBLE);
		add_video1.setImageResource(R.mipmap.img_video_01);
	}


	protected List<File> GetFilelist(){
		List<File> files= new ArrayList<>();

		for(FileIndexBean f:filelist){
			if(!f.isAdd()) {
				File imgfile = new File(f.getFileUrl());
				//ToastShow("SIZE:"+imgfile.length());
				Bitmap  mp =  ImageUtils.getBitmapFromFilePath(f.getFileUrl());
				File newFile = GetCommonParameters.saveFile(mp,imgfile.getName());
				files.add(newFile);
			}
		}

		if(vediofilelist.size()>0){
			files.add(vediofilelist.get(0));
		}

		return files;
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode  == Activity.RESULT_OK)  {
			if(data != null){
				Uri uri = data.getData();
				String url = GetCommonParameters.getRealFilePath(mContext,uri);
				showImage(url);
			}

		} else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && resultCode  == Activity.RESULT_OK) {
			showImage(capturePath);

		}else if(requestCode == REQUEST_CODE_CAPTURE_VIDEO && resultCode  == Activity.RESULT_OK){
			//压缩文件
			String out_file_path = Environment.getExternalStorageDirectory().getPath() + "/" + Config.APP_Code + "/video/thumb/";
			File dir = new File(out_file_path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			//获取文件名称
			String name = capturePath;
			int index = name.indexOf("video");
			String filename = name.substring(index+6,name.length());
			String videourl = out_file_path+ filename;
			compressVideoResouce(mContext,capturePath,videourl);
		}

	}



	/**
	 * 压缩视频
	 * @param mContext
	 * @param filepath
	 */
	public void compressVideoResouce(Context mContext, String filepath,final String newfilepath) {
		if (MyTextUtils.IsNullByString(filepath)) {
			ToastShow("请先选择转码文件！");
			return;
		}

		final LoadingDialog dialog = new LoadingDialog(mContext,"视频压缩中");
		dialog.show();

		//PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径
		PLShortVideoTranscoder mShortVideoTranscoder = new PLShortVideoTranscoder(mContext, filepath, newfilepath);
		MediaMetadataRetriever retr = new MediaMetadataRetriever();
		retr.setDataSource(filepath);
		String height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT); // 视频高度
		String width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH); // 视频宽度
		String rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION); // 视频旋转方向
		int transcodingBitrateLevel = 6;//我这里选择的2500*1000压缩，这里可以自己选择合适的压缩比例
		mShortVideoTranscoder.transcode(Integer.parseInt(width), Integer.parseInt(height), getEncodingBitrateLevel(transcodingBitrateLevel), false, new PLVideoSaveListener() {
			@Override
			public void onSaveVideoSuccess(String s) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						showVideoImage(newfilepath);
						dialog.close();
					}
				});
			}
			@Override
			public void onSaveVideoFailed(final int errorCode) {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						dialog.close();
						switch (errorCode) {
							case ERROR_NO_VIDEO_TRACK:
								ToastShow("该文件没有视频信息！");
								break;
							case ERROR_SRC_DST_SAME_FILE_PATH:
								ToastShow("源文件路径和目标路径不能相同！");
								break;
							case ERROR_LOW_MEMORY:
								ToastShow("手机内存不足，无法对该视频进行时光倒流！");
								break;
							default:
								ToastShow("transcode failed: " + errorCode);
						}
					}
				});
			}

			@Override
			public void onSaveVideoCanceled() {
//                LogUtil.e("onSaveVideoCanceled");
			}

			@Override
			public void onProgressUpdate(float percentage) {
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						showVideoImage(newfilepath);
//						ToastShow("压缩完成！");
//					}
//				});
				Log.d("info","onProgressUpdate==========" + percentage);
			}
		});
	}

	/**
	 * 设置压缩质量
	 *
	 * @param position
	 * @return
	 */
	private int getEncodingBitrateLevel(int position) {
		return ENCODING_BITRATE_LEVEL_ARRAY[position];
	}

	/**
	 * 选的越高文件质量越大，质量越好
	 */
	public static final int[] ENCODING_BITRATE_LEVEL_ARRAY = {
			500 * 1000,
			800 * 1000,
			1000 * 1000,
			1200 * 1000,
			1600 * 1000,
			2000 * 1000,
			2500 * 1000,
			4000 * 1000,
			8000 * 1000,
	};



}

